from flask import Flask
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import CSRFProtect
from redis import StrictRedis

from config import config

db = SQLAlchemy()


def create_app(config_name):
    app = Flask(__name__)
    # 加载配置
    app.config.from_object(config[config_name])
    # 初始化数据库
    db.init_app(app)

    redis_store = StrictRedis(host=config[config_name].REDIS_HOST, port=config[config_name].REDIS_PORT)
    # 开启当前项目CSRF保护
    # 1.校验2个csrf是否相等
    # 2.去生成一个csrf到表单中
    # 3.去生成一个csrf到cookie中
    # 4.请求的时候从请求中携带上cookie 在后端代码中接收cookie request.cookies.get("")
    # 5.从表单中接收token request.form.get('csrf_token')
    CSRFProtect(app)
    # 设置
    Session(app)

    return app
